<template>
  <div class="flex-column container">
    <div class="header radius shadow">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input
            placeholder="请你输入搜索用户名"
            v-model="keyword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            :disabled="keyword.length ? false : true"
            @click="search"
          >
            搜索
          </el-button>
          <el-button size="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content shadow radius flex-column">
      <div class="addHeader">
        <el-button type="primary" size="default" @click="addUser">
          添加</el-button
        >
        <el-button type="danger" size="default" @click="deleteSelectUser">
          批量删除</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table
        class="two-table"
        border
        :data="data.tableData"
        style="height: 100%; width: 100%"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          label="#"
          width="80"
          type="index"
          :index="1 + data.pageSize * (data.currentPage - 1)"
          align="center"
        ></el-table-column>
        <el-table-column
          label="id"
          prop="skuName"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户名字"
          prop="username"
          width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户名称"
          prop="name"
          width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户角色"
          prop="roleName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          align="center"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          prop="updateTime"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="320" align="center">
          <template #default="scope">
            <el-button size="small" icon="User" @click="setRole(scope.row)">
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateUser(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`你确定删除${scope.row.username}`"
              width="260px"
              @confirm="deleteUser(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[20, 40, 50, 80]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper,->sizes,total"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 用户的添加修改  抽屉 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? "更新用户" : "添加用户" }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请您输入用户姓名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请您输入用户昵称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input
              placeholder="请您输入用户密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分配角色 抽展结构：用户某一个已有的账号进行职位分配-->
    <el-drawer v-model="drawer1">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="职位列表">
            <!-- :indeterminate="isIndeterminate" 判断是否全选了，没有显示-  -->
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedUsersChange"
            >
              <el-checkbox
                v-for="(role, index) in allRole"
                :key="index"
                :label="role"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer1 = false">取消</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqSetUserRole,
  reqSelectUser,
  reqRemoveUser,
  reqAllRole,
} from "../../../api/acl/user/index";
import type {
  UserResponseData,
  User,
  AllRole,
  SetRoleData,
  AllRoleResponseData,
} from "../../../api/acl/user/type";
// 获取骨架的小仓库
import useLayoutSettingsStore from "../../../store/modules/settings";

const background = ref(true);
const size = ref("default");
const disabled = ref(false);

let formRef = ref<any>();
let keyword = ref<string>("");
const data = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  tableData: [],
});

let drawer = ref<boolean>(false);
let drawer1 = ref<boolean>(false);

let allRole = ref<AllRole>([]);
// 当前用户已有的职位
let userRole = ref<AllRole>([]);
// 收集用户信息的响应式数据
let userParams = reactive<User>({
  username: "",
  name: "",
  password: "",
});

let settingStore = useLayoutSettingsStore();
const checkAll = ref<boolean>(false);
const isIndeterminate = ref<boolean>(true);
// 准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<User[]>([]);

onMounted(() => {
  getHasUser();
});
//
const getHasUser = async () => {
  let res: UserResponseData = await reqUserInfo(
    data.currentPage,
    data.pageSize,
    keyword.value,
  );
  if (res.code === 200) {
    data.total = res.data.total;
    data.tableData = res.data.records as [];
  }
};
// 分页事件
//当下拉菜单发生变化的时候触发次方法
// //这个自定义事件,分页器组件会将下拉菜单选中数据返回
const handleSizeChange = (val: number) => {
  console.log(`每页 ${val} 条`);
  data.pageSize = val;
  data.currentPage = 1;
  getHasUser();
};

const handleCurrentChange = (val: number) => {
  console.log(`当前页: ${val}`);
  data.currentPage = val;
  getHasUser();
};
// 查询
const search = () => {
  getHasUser();
  keyword.value = "";
};

// 重置
const reset = () => {
  settingStore.refsh = !settingStore.refsh;
};

// 添加用户信息
const addUser = () => {
  drawer.value = true;
  // 清空数据
  Object.assign(userParams, {
    id: 0,
    username: "",
    name: "",
    password: "",
  });
  // 延迟执行 去处理清除上一次的校验
  nextTick(() => {
    formRef.value.clearValidate("username");
    formRef.value.clearValidate("name");
    formRef.value.clearValidate("password");
  });
};
// 更新用户信息
const updateUser = (row: User) => {
  drawer.value = true;
  Object.assign(userParams, row);
  nextTick(() => {
    formRef.value.clearValidate("username");
    formRef.value.clearValidate("name");
  });
};
// 删除某个用户信息
const deleteUser = async (userId: number) => {
  let res: any = await reqRemoveUser(userId);
  if (res.code === 200) {
    ElMessage({ type: "success", message: "删除成功" });
    data.currentPage =
      data.tableData.length > 1 ? data.currentPage : data.currentPage - 1;
    getHasUser();
  }
};
// 批量删除
const deleteSelectUser = async () => {
  let idList: any = selectIdArr.value.map((item: any) => {
    return item.id;
  });
  let res: any = await reqSelectUser(idList);
  if (res.code === 200) {
    ElMessage({ type: "success", message: "删除成功" });
    data.currentPage =
      data.tableData.length > 1 ? data.currentPage : data.currentPage - 1;
    getHasUser();
  }
};

// 抽屉的保存
const save = async () => {
  formRef.value.validate();
  let res: any = await reqAddOrUpdateUser(userParams);
  if (res.code === 200) {
    drawer.value = false;
    ElMessage({
      type: "success",
      message: userParams.id ? "更新成功" : "添加成功",
    });
    // 自动刷新浏览器、刷新页面去我们的路由守卫，判断账号是否有没有重新登陆
    window.location.reload();
    //getHasUser()
  } else {
    drawer.value = false;
    ElMessage({
      type: "error",
      message: userParams.id ? "更新失败" : "添加失败",
    });
  }
};

// 抽屉的取消
const cancel = () => {
  drawer.value = false;
};

// 分配角色  顶部的全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : [];
  isIndeterminate.value = false;
};

// 复选框事件 顶部全部的复选框的change事件
const handleCheckedUsersChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === allRole.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length;
};
// 分配角色 打开弹框
const setRole = async (row: User) => {
  drawer1.value = true;
  Object.assign(userParams, row);
  let res: AllRoleResponseData = await reqAllRole(userParams.id as number);
  if (res.code === 200) {
    // 存储全部职位的数组
    allRole.value = res.data.allRolesList;
    userRole.value = res.data.assignRoles;
    drawer1.value = true;
  }
};
// 分配角色 的保存
const confirmClick = async () => {
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item: any) => {
      return item.id as number;
    }),
  };
  let res: any = await reqSetUserRole(data);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "分配职务成功",
    });
    drawer1.value = false;
    getHasUser();
  }
};

// 表单校验规则的自定义
// 自定义校验规格 页面上面的必填校验
const validatorUserName = (rule: any, value: any, callBack: any) => {
  console.log(rule);
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("用户名字至少五位"));
  }
};

// 自定义校验规格
const validatorName = (rule: any, value: any, callBack: any) => {
  console.log(rule);
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("用户昵称至少五位"));
  }
};

// 自定义校验规格
const validatorPassword = (rule: any, value: any, callBack: any) => {
  console.log(rule);
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("用户密码至少六位"));
  }
};
// 表单校验的规则对象
const rules = {
  // 用户名称
  username: [{ required: true, trigger: "blur", validator: validatorUserName }],
  // 账号
  name: [{ required: true, trigger: "blur", validator: validatorName }],
  // 密码
  password: [{ required: true, trigger: "blur", validator: validatorPassword }],
};
</script>

<style scoped lang="scss">
@import "@/styles/common.scss";

.header {
  padding: 10px;
  box-sizing: border-box;
  height: 60px;
  width: 100%;
  margin-bottom: 10px;

  .form {
    margin-top: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.content {
  flex: 1;
  box-sizing: border-box;
  overflow: hidden;
  padding: 12px;

  .addHeader {
    height: 40px;
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>
